package cn.wizzer.app.web.modules.controllers.open;

import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.BizTypeEnum;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.user.modules.services.account.UserAccountRecordService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.filter.ParamFilter;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import java.math.BigDecimal;

@IocBean
@At("/api/test")
@Api("ApiToken测试")
@Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
public class ApiTestController {
    private final static Log log = Logs.get();

    @Inject
    @Reference
    private UserService userService;

    @Inject
    @Reference
    private UserAccountRecordService userAccountRecordService;

    @Inject
    @Reference
    private SysParamService sysParamService;

    @At
    @Ok("json")
    public void recharge(String appid, String amount) {
        if (sysParamService.fetch().isDebug())
            userAccountRecordService.add(appid, new BigDecimal(amount), BizTypeEnum.RECHARGE, appid);
    }

    @At
    @Ok("json")
    public void updateUser(String userStr) {
        if (sysParamService.fetch().isDebug())
            userService.updateUser(JSONUtil.parseJavaBean(User.class, userStr));
    }

    @At
    @Ok("json")
    public Result fetchUserByPhone(String phone) {
        if (sysParamService.fetch().isDebug())
            return Result.success(userService.fetch(Cnd.where("phone", "=", phone)));
        return Result.error("sysParamService.fetch().isDebug():false");
    }

    @At
    @Ok("json")
    public String fetchInviteCodeByPhone(String phone) {
        User user = userService.fetch(Cnd.where("phone", "=", phone));
        if (user == null) {
            return "User(phone=" + phone + ") does not exist";
        }
        if (sysParamService.fetch().isDebug())
            return user.getInviteCode();
        return "sysParamService.fetch().isDebug():false";
    }
}
